package com.aismy.admin.service.impl;

import com.aismy.admin.entity.EduResource;
import com.aismy.admin.mapper.EduResourceMapper;
import com.aismy.admin.service.EduResourceService;
import com.aismy.admin.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class EduResourceServiceImpl extends ServiceImpl<EduResourceMapper, EduResource> implements EduResourceService {

    @Value("${upload.video.path}")
    private String uploadPath;
    
    @Value("${upload.video.url-prefix}")
    private String urlPrefix;

    @Override
    public Page<EduResource> listResources(Integer current, Integer size, String title, String type) {
        Page<EduResource> page = new Page<>(current, size);
        
        LambdaQueryWrapper<EduResource> wrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        if (StringUtils.hasText(title)) {
            wrapper.like(EduResource::getTitle, title);
        }
        if (StringUtils.hasText(type)) {
            wrapper.eq(EduResource::getType, type);
        }
        // 按创建时间倒序排序
        wrapper.orderByDesc(EduResource::getCreatedAt);
        
        return page(page, wrapper);
    }

    @Override
    public String uploadVideo(MultipartFile file) {
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!".mp4".equals(extension) && !".mov".equals(extension) && !".avi".equals(extension)) {
            throw new BusinessException("不支持的文件格式");
        }
        
        // 检查文件大小（500MB）
        if (file.getSize() > 500 * 1024 * 1024) {
            throw new BusinessException("文件大小不能超过500MB");
        }
        // 生成新的文件名
        String newFileName = UUID.randomUUID().toString() + extension;
        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 保存文件
        try {
            File destFile = new File(uploadPath + File.separator + newFileName);
            file.transferTo(destFile);
            
            // 返回可访问的URL
            return urlPrefix + "/" + newFileName;
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        EduResource resource = getById(id);
        if (resource == null) {
            throw new BusinessException("资源不存在");
        }
        
        resource.setStatus(status);
        updateById(resource);
    }

    @Override
    public void incrementViewCount(Long id) {
        // 使用update方法更新浏览量
        update()
            .setSql("view_count = view_count + 1")
            .eq("id", id)
            .update();
    }
} 